﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DG.Common.Validation
{
    public class ValidatorCollection : IEnumerable<IValidator>
    {
        private readonly HashSet<IValidator> _validators = new HashSet<IValidator>();
        public MethodValidator AddMethodValidator(Func<bool> methodValidator,Func<string> errorMessage = null, Func<bool> preCondition = null)
        {
            var validator = new MethodValidator(methodValidator, errorMessage, preCondition);
            _validators.Add(validator);
            
            return validator;
        }
        
        public bool IsValid()
        {
            return this.All(v => v.IsValid);
        }

        public bool RemoveValidator(IValidator item)
        {
            return _validators.Remove(item);
        }

        public IEnumerable<IValidator> GetErrorList()
        {
            return this.Where(v => !v.IsValid);
        }

        public string GetErrorListMessage()
        {
            return string.Join(Environment.NewLine, GetErrorList().Select(v => v.ErrorMessage()));
        }

        public IEnumerator<IValidator> GetEnumerator()
        {
            return _validators.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
